package com.tyqx.biz;


import com.sun.mail.smtp.SMTPTransport;
import com.tyqx.bean.model.SubServerInfo;
import com.tyqx.bean.model.SubServerSendInfo;
import com.tyqx.service.SubServerInfoService;
import com.tyqx.service.SubServerSendInfoService;
import com.tyqx.util.PrintDirUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

@Component
public class SchedulerSubServerNetworkInterruptionSendMessage {

    private static final Logger logger = LoggerFactory.getLogger(SchedulerSubServerNetworkInterruptionSendMessage.class);


    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private Constant constant;

    @Value("${emailMessage.fromEmail}")
    private String fromEmail;

    @Value("${emailMessage.toEmail}")
    private  String toEmail;

    @Value("${emailMessage.username}")
    private String username;

    @Value("${emailMessage.password}")
    private  String password;

    @Value("${emailMessage.smtpServer}")
    private  String smtpServer;

    private static String toEmailCC = "";

    private static String emailSubject = "子服务器网络中断!";

    private static String emailText = "";

    Integer pingCount = 0;

    Integer count = 0;

    private List<String> beforeubServerErrorList = new ArrayList<>();

    private String afterSubServerAddress = "";


    @Resource
    private SubServerInfoService subServerInfoService;

    @Resource
    private SubServerSendInfoService subServerSendInfoService;


    //表示每隔秒
    @Scheduled(fixedRate = 60 * 1000 * 1)
    //@Scheduled(fixedDelay = 1000 * 60 * 1)
    public void testTasks() throws Exception {
        logger.info("检测子服务器网络定时器开始执行："+dateFormat.format(new Date())+"\n");

        int pingTimes = 2;

        int timeout = 3000;

        List<String> subServerErrorList = new ArrayList<>();
        try{
            boolean flag = false;

            List<SubServerInfo> subServerInfoList = subServerInfoService.selectSubServerInfos();
            String emailTextErrorComputName = "";
            if(subServerInfoList.size()>0) {
                for (SubServerInfo subServerInfo:subServerInfoList){
                    String computName = subServerInfo.getComputName();
                    logger.info("computerName:"+computName);
                    List<SubServerSendInfo> subServerSendInfoList = subServerSendInfoService.selectSubServerSendInfoByComputName(computName);
                    if(subServerSendInfoList.size() == 0){
                        logger.info(computName+"还未发送过数据，跳过");
                        continue;
                    }
                    SubServerSendInfo subServerSendInfo = subServerSendInfoList.get(0);
                    Date sendDataDate = subServerSendInfo.getCreateDate();
                    long currentTime =System.currentTimeMillis();
                    //从对象中拿到时间
                    long createTime = dateFormat.parse(dateFormat.format(sendDataDate)).getTime();
                    long diff=(currentTime-createTime)/1000/60;
                    if(diff > 1){
                        logger.info(computName+"传输数据超时："+diff+"，最后一次发送消息时间："+dateFormat.format(sendDataDate));
                        subServerErrorList.add(computName);
                        if(("").equals(emailTextErrorComputName)){
                            emailTextErrorComputName = computName;

                        }else{
                            emailTextErrorComputName = emailTextErrorComputName + "," + computName;
                        }
                    }else{
                        logger.info(computName+"传输数据正常，最后一次发送消息时间："+dateFormat.format(sendDataDate));
                    }
                }
                if (!"".equals(emailTextErrorComputName)) {
                    emailText = "\t 停止发送消息的计算器名称：\t" + emailTextErrorComputName;
                    pingCount = pingCount + 1;
                    logger.info(emailTextErrorComputName + ">>>>停止发送消息的计算器名称:" + pingCount + "分钟");
                } else {
                    logger.info("子服务器发送消息正常");
                    pingCount = 0;
                }


                if (pingCount > 3) {
                    emailText = emailText + "\n\n\t最长中断时间超过"+pingCount+"分钟";
                    logger.info(emailTextErrorComputName + ">>>>>>>>>>停止发送消息的计算器名称" + pingCount + "分钟");
                    if (pingCount == 4) {
                        logger.info("发送消息");
                        beforeubServerErrorList = subServerErrorList;
                        flag = true;
                    }
                    if (pingCount > 4) {
                        if (PrintDirUtil.compare(subServerErrorList,beforeubServerErrorList).size() == 0) {
                            if (pingCount == 30) {
                                logger.info("发送消息");
                                flag = true;
                            }
                            if (pingCount == 60) {
                                logger.info("发送消息");
                                flag = true;
                            }
                            if (pingCount > 100) {
                                pingCount = 0;
                            }
                        } else {
                            logger.info("得到的集合不相等，重新发送，不会累积时间");
                            pingCount = 0;
                        }
                    }
                }
            }


            if(flag){

//                Properties prop = System.getProperties();
//                prop.put("mail.smtp.host", smtpServer); //optional, defined in SMTPTransport
//                prop.put("mail.smtp.auth", "true");
//                prop.put("mail.smtp.starttls.enable", "true");
//                prop.put("mail.smtp.ssl.trust", smtpServer);
//                prop.put("mail.smtp.port", "465"); // default port 25
//                prop.put("mail.SSLOnConnect","true"); //25 false 465 true

                Properties props = new Properties();
                props.put("mail.smtp.host", smtpServer);
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.fallback", "false");
                props.put("mail.smtp.port", "465");
                props.put("mail.smtp.socketFactory.port", "465"); //Linux下需要设置此项，Windows默认localhost为127.0.0.1
                props.put("mail.smtp.localhost", "127.0.0.1");
                //鉴权验证
                props.put("mail.smtp.auth", "true");


                Session session = Session.getInstance(props, null);
                Message msg = new MimeMessage(session);

                try {

                    // from
                    msg.setFrom(new InternetAddress(fromEmail));

                    // to
                    msg.setRecipients(Message.RecipientType.TO,
                            InternetAddress.parse(toEmail, false));

                    // cc
                    msg.setRecipients(Message.RecipientType.CC,
                            InternetAddress.parse(toEmailCC, false));

                    // subject
                    msg.setSubject(emailSubject);

                    // content
                    msg.setText(emailText);


                    msg.setSentDate(new Date());

                    // Get SMTPTransport
                    SMTPTransport t = (SMTPTransport) session.getTransport("smtp");

                    // connect
                    t.connect(smtpServer, username, password);

                    // send
                    t.sendMessage(msg, msg.getAllRecipients());

                    logger.info("Response: " + t.getLastServerResponse());

                    t.close();

                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        logger.info("检测子服务器网络定时器结束执行："+dateFormat.format(new Date())+"\n");
    }


    @Scheduled(fixedRate = 60 * 1000 * 30)
    public void deleteSendData() throws Exception {
        logger.info("删除子服务器发送的数据定时器开始执行："+dateFormat.format(new Date())+"\n");
        try{
            List<SubServerInfo> subServerInfoList = subServerInfoService.selectSubServerInfos();
            for (int i=0;i<subServerInfoList.size();i++){
                SubServerInfo subServerInfo = subServerInfoList.get(i);
                String computName = subServerInfo.getComputName();
                List<SubServerSendInfo> subServerSendInfoList = subServerSendInfoService.selectSubServerSendInfoByComputName(computName);
                subServerSendInfoList.remove(0);
                for (int j = 0; j < subServerSendInfoList.size(); j++){
                    SubServerSendInfo subServerSendInfo = subServerSendInfoList.get(j);
                    if(subServerSendInfoService.delete(subServerSendInfo.getId())){
                        logger.info("computName:"+computName+",id:"+subServerSendInfo.getId()+"删除成功");
                    }else{
                        logger.info("computName:"+computName+",id:"+subServerSendInfo.getId()+"删除失败");
                    }
                }
            }
        }catch (Exception e){
            logger.error("删除子服务器发送的数据错误");
            e.printStackTrace();
        }

        logger.info("删除子服务器发送的数据定时器结束执行："+dateFormat.format(new Date())+"\n");
    }
}